<?php

namespace App\Http\Controllers\Api;

use Overtrue\EasySms\EasySms;
use App\Http\Requests\Api\VerificationCodeRequest;

class VerificationCodesController extends Controller
{
    public function store(VerificationCodeRequest $request, EasySms $easySms)
    {
        $user_mobile = $request->user_mobile;
        $code = '666666'; // 非生产环境

        if (app()->environment('production')) {
            // 生成6位随机数，左侧补0
            $code = str_pad(random_int(1, 999999), 6, 0, STR_PAD_LEFT);

            try {
                $easySms->send($user_mobile, [
                    'template' => config('app.qcloud_sms_template'),
                    'data' => [
                        'code' => $code
                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                \Log::error($exception->getException('qcloud')->getMessage());
                return $this->failed('短信发送失败');
            }
        }

        $key = 'verificationCode_' . str_random(15);
        $expiredAt = now()->addMinutes(5);
        // 验证码缓存 5 分钟
        \Cache::put($key, ['tel' => $user_mobile, 'code' => $code], $expiredAt);

        return $this->success(['key' => $key, 'expired_at' => $expiredAt->toDateTimeString()]);
    }

    public static function verify($user_mobile, $key, $code)
    {
        // 校验验证码
        $verifyData = \Cache::get($key);

        if (!$verifyData) {
            return ['message' => '验证码已失效', 'response' => 'failed'];
        }

        if (!hash_equals($verifyData['code'], $code)) {
            return ['message' => '验证码错误', 'response' => 'failed'];
        }

        if (!hash_equals($verifyData['tel'], $user_mobile)) {
            return ['message' => '手机号错误', 'response' => 'failed'];
        }

        // 验证成功，清除验证码缓存
        \Cache::forget($key);

        return ['response' => 'success', 'message' => ''];
    }

}